class SalaryCalculator {
    constructor() {
        this.monthlySalary = 0;
        this.startTime = '';
        this.endTime = '';
        this.lunchBreak = 1; // 默认1小时休息
        this.workDaysPerWeek = 5;
        this.isProbationPeriod = false;
        this.dailySalary = 0;
        this.perSecondEarnings = 0;
        this.perMinuteEarnings = 0;
        this.perHourEarnings = 0;
        this.workDaysInMonth = 0;
        this.workDurationSeconds = 0;
        this.currentEarnings = 0;
        this.isTracking = false;
        this.isPaused = false;
        this.intervalId = null;
        this.startTimestamp = null;
        this.pausedTime = 0;
        this.workStartTime = null;
        this.workEndTime = null;
        
        // 月度总收入相关
        this.monthlyTotalEarnings = 0;
        this.workDaysCompleted = 0;

        this.initializeElements();
        this.bindEvents();
        this.loadFromCache();
    }

    initializeElements() {
        // Form elements
        this.form = document.getElementById('salaryForm');
        this.monthlySalaryInput = document.getElementById('monthlySalary');
        this.isProbationPeriodInput = document.getElementById('isProbationPeriod');
        this.workDaysPerWeekInput = document.getElementById('workDaysPerWeek');
        this.startTimeInput = document.getElementById('startTime');
        this.endTimeInput = document.getElementById('endTime');
        this.lunchBreakInput = document.getElementById('lunchBreak');

        // Step containers
        this.setupStep = document.getElementById('setupStep');
        this.earningsStep = document.getElementById('earningsStep');
        this.settlementStep = document.getElementById('settlementStep');
        
        // Display elements
        this.earningsCard = document.getElementById('earningsCard');
        this.currentEarningsDisplay = document.getElementById('currentEarnings');
        this.progressFill = document.getElementById('progressFill');
        this.progressPercentage = document.getElementById('progressPercentage');
        this.timeRemaining = document.getElementById('timeRemaining');

        // Stats elements
        this.perSecondDisplay = document.getElementById('perSecondEarnings');
        this.perMinuteDisplay = document.getElementById('perMinuteEarnings');
        this.perHourDisplay = document.getElementById('perHourEarnings');
        this.dailyTargetDisplay = document.getElementById('dailyTarget');
        this.workDaysDisplay = document.getElementById('workDaysCount');
        this.workDurationDisplay = document.getElementById('workDuration');
        this.probationStatusDisplay = document.getElementById('probationStatus');
        this.monthlyTotalDisplay = document.getElementById('monthlyTotalEarnings');

        // Control buttons
        this.startTrackingBtn = document.getElementById('startTrackingBtn');
        this.pauseBtn = document.getElementById('pauseBtn');
        this.miniModeBtn = document.getElementById('miniModeBtn');
        this.resetBtn = document.getElementById('resetBtn');
        this.backToSetupBtn = document.getElementById('backToSetup');
        
        // Mini window elements
        this.miniWindow = document.getElementById('miniWindow');
        this.expandBtn = document.getElementById('expandBtn');
        this.closeMiniBtn = document.getElementById('closeMiniBtn');
        this.miniCurrentEarnings = document.getElementById('miniCurrentEarnings');
        this.miniProgressFill = document.getElementById('miniProgressFill');
        this.miniProgressPercentage = document.getElementById('miniProgressPercentage');
        this.miniTimeRemaining = document.getElementById('miniTimeRemaining');
        this.miniPauseBtn = document.getElementById('miniPauseBtn');
        this.miniStartBtn = document.getElementById('miniStartBtn');
        
        // Mini window state
        this.isMiniMode = false;
        this.isDragging = false;
        this.dragOffset = { x: 0, y: 0 };
    }

    bindEvents() {
        this.form.addEventListener('submit', (e) => this.handleFormSubmit(e));
        this.startTrackingBtn.addEventListener('click', () => this.startTracking());
        this.pauseBtn.addEventListener('click', () => this.togglePause());
        this.miniModeBtn.addEventListener('click', () => this.enterMiniMode());
        this.resetBtn.addEventListener('click', () => this.reset());
        this.backToSetupBtn.addEventListener('click', () => this.backToSetup());
        
        // Settlement page events
        this.backToEarningsBtn = document.getElementById('backToEarnings');
        this.newDayBtn = document.getElementById('newDayBtn');
        this.shareResultBtn = document.getElementById('shareResultBtn');
        
        this.backToEarningsBtn.addEventListener('click', () => this.backToEarnings());
        this.newDayBtn.addEventListener('click', () => this.startNewDay());
        this.shareResultBtn.addEventListener('click', () => this.shareResult());
        
        // Mini window events
        this.expandBtn.addEventListener('click', () => this.exitMiniMode());
        this.closeMiniBtn.addEventListener('click', () => this.closeMiniWindow());
        this.miniPauseBtn.addEventListener('click', () => this.togglePause());
        this.miniStartBtn.addEventListener('click', () => this.startTracking());
        
        // Mini window drag functionality
        this.setupMiniWindowDrag();
    }

    handleFormSubmit(e) {
        e.preventDefault();
        
        this.monthlySalary = parseFloat(this.monthlySalaryInput.value);
        this.isProbationPeriod = this.isProbationPeriodInput.checked;
        this.workDaysPerWeek = parseFloat(this.workDaysPerWeekInput.value);
        this.startTime = this.startTimeInput.value;
        this.endTime = this.endTimeInput.value;
        this.lunchBreak = parseFloat(this.lunchBreakInput.value) || 0;

        if (!this.monthlySalary || !this.workDaysPerWeek || !this.startTime || !this.endTime) {
            alert('请填写完整信息！');
            return;
        }

        if (this.startTime >= this.endTime) {
            alert('下班时间必须晚于上班时间！');
            return;
        }

        this.calculate();
        this.saveToCache();
        this.startTracking();
    }

    calculate() {
        // 计算当月工作日数量
        this.workDaysInMonth = this.getWorkDaysInCurrentMonth();
        
        // 计算每日工资（试用期打8折）
        let baseDailySalary = this.monthlySalary / this.workDaysInMonth;
        this.dailySalary = this.isProbationPeriod ? baseDailySalary * 0.8 : baseDailySalary;
        
        // 计算工作时长（秒）
        this.workDurationSeconds = this.calculateWorkDurationInSeconds();
        
        // 计算各种收入单位
        this.perSecondEarnings = this.dailySalary / this.workDurationSeconds;
        this.perMinuteEarnings = this.perSecondEarnings * 60;
        this.perHourEarnings = this.perSecondEarnings * 3600;

        // 更新显示
        this.updateStats();
    }

    getWorkDaysInCurrentMonth() {
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth();
        const daysInMonth = new Date(year, month + 1, 0).getDate();
        
        // 计算当月的总周数
        const weeksInMonth = daysInMonth / 7;
        
        // 根据每周工作天数计算总工作日
        let workDays = Math.round(weeksInMonth * this.workDaysPerWeek);
        
        // 对于更精确的计算，我们也可以检查具体的日期
        if (this.workDaysPerWeek <= 5) {
            // 对于传统工作制，精确计算周一到周五的天数
            let exactWorkDays = 0;
            for (let day = 1; day <= daysInMonth; day++) {
                const date = new Date(year, month, day);
                const dayOfWeek = date.getDay();
                
                // 根据工作天数判断工作日
                if (this.workDaysPerWeek >= 5 && dayOfWeek >= 1 && dayOfWeek <= 5) {
                    exactWorkDays++;
                } else if (this.workDaysPerWeek === 4 && dayOfWeek >= 1 && dayOfWeek <= 4) {
                    exactWorkDays++;
                } else if (this.workDaysPerWeek === 4.5) {
                    if (dayOfWeek >= 1 && dayOfWeek <= 4) {
                        exactWorkDays++;
                    } else if (dayOfWeek === 5) {
                        exactWorkDays += 0.5; // 半天
                    }
                }
            }
            
            // 如果是传统工作制，使用精确计算
            if (this.workDaysPerWeek <= 5) {
                workDays = exactWorkDays;
            }
        }
        
        // 确保至少有1个工作日
        return Math.max(1, workDays);
    }

    calculateWorkDurationInSeconds() {
        const [startHours, startMinutes] = this.startTime.split(':').map(Number);
        const [endHours, endMinutes] = this.endTime.split(':').map(Number);
        
        const startTimeInMinutes = startHours * 60 + startMinutes;
        const endTimeInMinutes = endHours * 60 + endMinutes;
        
        const totalDurationInMinutes = endTimeInMinutes - startTimeInMinutes;
        
        // 减去中午休息时间（转换为分钟）
        const lunchBreakMinutes = this.lunchBreak * 60;
        const actualWorkMinutes = Math.max(0, totalDurationInMinutes - lunchBreakMinutes);
        
        return actualWorkMinutes * 60; // 转换为秒
    }
    
    calculateTotalWorkDurationInSeconds() {
        const [startHours, startMinutes] = this.startTime.split(':').map(Number);
        const [endHours, endMinutes] = this.endTime.split(':').map(Number);
        
        const startTimeInMinutes = startHours * 60 + startMinutes;
        const endTimeInMinutes = endHours * 60 + endMinutes;
        
        const totalDurationInMinutes = endTimeInMinutes - startTimeInMinutes;
        
        return totalDurationInMinutes * 60; // 转换为秒，不减去休息时间
    }
    
    // 计算月度总收入
    calculateMonthlyTotalEarnings() {
        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth();
        
        // 获取本月1号
        const monthStart = new Date(currentYear, currentMonth, 1);
        
        // 获取当前日期
        const currentDate = new Date(currentYear, currentMonth, now.getDate());
        
        // 计算从本月1号到当前日期的天数
        const daysDiff = Math.floor((currentDate - monthStart) / (1000 * 60 * 60 * 24)) + 1;
        
        // 计算已完成的工作日数（不包括今天）
        let completedWorkDays = 0;
        
        for (let day = 1; day < daysDiff; day++) {
            const checkDate = new Date(currentYear, currentMonth, day);
            const dayOfWeek = checkDate.getDay();
            
            // 根据每周工作天数判断是否为工作日
            if (this.isWorkDay(checkDate)) {
                completedWorkDays++;
            }
        }
        
        // 计算已完成工作日的总收入
        this.workDaysCompleted = completedWorkDays;
        this.monthlyTotalEarnings = completedWorkDays * this.dailySalary;
        
        return this.monthlyTotalEarnings;
    }
    
    // 判断指定日期是否为工作日
    isWorkDay(date) {
        const dayOfWeek = date.getDay();
        
        if (this.workDaysPerWeek >= 5 && dayOfWeek >= 1 && dayOfWeek <= 5) {
            return true;
        } else if (this.workDaysPerWeek === 4 && dayOfWeek >= 1 && dayOfWeek <= 4) {
            return true;
        } else if (this.workDaysPerWeek === 4.5) {
            if (dayOfWeek >= 1 && dayOfWeek <= 4) {
                return true;
            } else if (dayOfWeek === 5) {
                return true; // 半天也算工作日
            }
        } else if (this.workDaysPerWeek === 6 && dayOfWeek >= 1 && dayOfWeek <= 6) {
            return true;
        } else if (this.workDaysPerWeek === 7) {
            return true; // 每天都是工作日
        }
        
        return false;
    }

    updateStats() {
        this.perSecondDisplay.textContent = this.perSecondEarnings.toFixed(4);
        this.perMinuteDisplay.textContent = this.perMinuteEarnings.toFixed(2);
        this.perHourDisplay.textContent = this.perHourEarnings.toFixed(2);
        this.dailyTargetDisplay.textContent = this.dailySalary.toFixed(2);
        this.workDaysDisplay.textContent = this.workDaysInMonth;
        // 显示实际工作时长（减去休息时间）
        this.workDurationDisplay.textContent = (this.workDurationSeconds / 3600).toFixed(1);
        
        // 计算并更新月度总收入
        this.calculateMonthlyTotalEarnings();
        this.monthlyTotalDisplay.textContent = this.monthlyTotalEarnings.toFixed(2);
        
        // 隐藏试用期状态显示
        this.probationStatusDisplay.style.display = 'none';
    }

    startTracking() {
        if (this.isTracking) {
            this.stopTracking();
        }

        // 检查是否在工作时间内
        const now = new Date();
        const currentTimeString = now.toTimeString().substr(0, 5);
        
        if (currentTimeString < this.startTime) {
            alert(`还没到上班时间！上班时间是 ${this.startTime}`);
            return;
        }

        if (currentTimeString > this.endTime) {
            alert(`已过下班时间！下班时间是 ${this.endTime}`);
            return;
        }

        this.isTracking = true;
        this.isPaused = false;
        this.startTimestamp = Date.now();
        this.pausedTime = 0;
        
        // 计算今天的工作开始和结束时间戳
        const today = new Date();
        this.workStartTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 
            ...this.startTime.split(':').map(Number));
        this.workEndTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 
            ...this.endTime.split(':').map(Number));

        this.hideStartTrackingButton();
        this.showEarningsStep();
        this.updateDisplay();
        
        this.intervalId = setInterval(() => {
            this.updateDisplay();
        }, 1000); // 每秒更新一次
    }

    updateDisplay() {
        if (!this.isTracking || this.isPaused) return;

        const now = Date.now();
        const workStartTimestamp = this.workStartTime.getTime() ;
        const elapsedSeconds = Math.max(0, (now - workStartTimestamp) / 1000);
        
        // 计算当前收入（基于实际工作时长）
        this.currentEarnings = Math.min( (elapsedSeconds -this.lunchBreak * 60*60) * this.perSecondEarnings, this.dailySalary);
   
        // 更新主界面显示
        this.currentEarningsDisplay.textContent = this.currentEarnings.toFixed(4);
        
        // 计算总工作时长（从上班到下班，包括休息时间）
        const totalWorkDurationSeconds = this.calculateTotalWorkDurationInSeconds();
        
        // 更新进度条（基于总工作时长，这样进度条会准确反映时间进度）
        const progressPercentage = Math.min((elapsedSeconds / totalWorkDurationSeconds) * 100, 100);
        this.progressFill.style.width = progressPercentage + '%';
        this.progressPercentage.textContent = progressPercentage.toFixed(1) + '%';
        
        // 更新剩余时间（基于总工作时长，这样剩余时间显示正确）
        const remainingSeconds = Math.max(0, totalWorkDurationSeconds - elapsedSeconds);
        this.timeRemaining.textContent = `剩余时间: ${this.formatTime(remainingSeconds)}`;
        
        // 同步更新小窗模式显示
        this.updateMiniDisplay(progressPercentage, remainingSeconds);
        
        // 检查是否到下班时间（基于固定的下班时间）
        const currentTime = new Date();
        if (currentTime >= this.workEndTime) {
            this.completeWorkDay();
        }
    }

    formatTime(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = Math.floor(seconds % 60);
        
        return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }



    stopTracking() {
        this.isTracking = false;
        this.isPaused = false;
        
        if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
        }
        
        this.pauseBtn.innerHTML = '⏸ 暂停';
        this.pauseBtn.style.background = 'rgba(255, 255, 255, 0.8)';
        this.pauseBtn.style.color = '#667eea';
        
        // 显示开始追踪按钮，允许重新开始
        this.showStartTrackingButton();
    }

    completeWorkDay() {
        this.stopTracking();
        
        // 显示完成提示
        this.currentEarnings = this.dailySalary;
        this.currentEarningsDisplay.textContent = this.currentEarnings.toFixed(2);
        this.progressFill.style.width = '100%';
        this.progressPercentage.textContent = '100%';
        this.timeRemaining.textContent = '今日工作完成！🎉';
        
        // 添加完成动画
        this.progressFill.style.background = 'linear-gradient(90deg, #28a745 0%, #20c997 100%)';
        
        // 隐藏开始追踪按钮，工作已完成
        this.hideStartTrackingButton();
        
        // 延迟1秒后显示结算页面
        setTimeout(() => {
            this.showSettlementPage();
                 // 确保窗口恢复到正常尺寸
            this.isMiniMode = false;
            this.miniWindow.style.display = 'none';
            document.body.style.overflow = ''; // 恢复滚动条
            
            // 恢复主窗口到正常尺寸（Electron环境）
            if (window.electronAPI) {
                window.electronAPI.resizeWindowToNormal();
            }
        }, 1000);
    }

    showEarningsStep() {
        this.setupStep.style.display = 'none';
        this.settlementStep.style.display = 'none';
        this.earningsStep.style.display = 'block';
        
        // 添加显示动画
        setTimeout(() => {
            this.earningsStep.style.opacity = '1';
            this.earningsStep.style.transform = 'translateX(0)';
        }, 100);
    }

    showSetupStep() {
        this.earningsStep.style.display = 'none';
        this.settlementStep.style.display = 'none';
        this.setupStep.style.display = 'block';
        
        // 添加显示动画
        setTimeout(() => {
            this.setupStep.style.opacity = '1';
            this.setupStep.style.transform = 'translateX(0)';
        }, 100);
    }
    
    showSettlementPage() {
        // 隐藏其他页面
        this.setupStep.style.display = 'none';
        this.earningsStep.style.display = 'none';
        this.settlementStep.style.display = 'block';
        
        // 更新结算页面数据
        this.updateSettlementData();
        
        // 添加显示动画
        setTimeout(() => {
            this.settlementStep.style.opacity = '1';
            this.settlementStep.style.transform = 'translateX(0)';
        }, 100);
    }
    
    updateSettlementData() {
        // 更新结算页面显示的数据
        document.getElementById('settlementDailyEarnings').textContent = this.currentEarnings.toFixed(2);
        document.getElementById('settlementWorkDuration').textContent = (this.workDurationSeconds / 3600).toFixed(1);
        document.getElementById('settlementProgress').textContent = '100%';
        document.getElementById('settlementPerSecond').textContent = this.perSecondEarnings.toFixed(4);
        document.getElementById('settlementPerMinute').textContent = this.perMinuteEarnings.toFixed(2);
        document.getElementById('settlementPerHour').textContent = this.perHourEarnings.toFixed(2);
        document.getElementById('settlementMonthlyTotal').textContent = this.monthlyTotalEarnings.toFixed(2);
    }

    backToSetup() {
        this.stopTracking();
        this.showSetupStep();
        
        // 重置进度显示
        this.currentEarnings = 0;
        this.currentEarningsDisplay.textContent = '0.00';
        this.progressFill.style.width = '0%';
        this.progressPercentage.textContent = '0%';
        this.timeRemaining.textContent = '剩余时间: --:--';
        
        // 重置月度总收入显示
        this.monthlyTotalDisplay.textContent = '0.00';
        
        // 重置进度条颜色
        this.progressFill.style.background = 'linear-gradient(90deg, #667eea 0%, #764ba2 100%)';
        
        // 隐藏试用期状态
        this.probationStatusDisplay.style.display = 'none';
        
        // 隐藏开始追踪按钮
        this.hideStartTrackingButton();
        
        // 重置中午休息时长
        this.lunchBreak = 1;
        this.lunchBreakInput.value = '1';
    }
    
    // 结算页面相关方法
    backToEarnings() {
        this.settlementStep.style.display = 'none';
        this.showEarningsStep();
    }
    
    startNewDay() {
        // 重置今日数据，准备新的一天
        this.currentEarnings = 0;
        this.currentEarningsDisplay.textContent = '0.00';
        this.progressFill.style.width = '0%';
        this.progressFill.style.background = 'linear-gradient(90deg, #667eea 0%, #764ba2 100%)';
        this.progressPercentage.textContent = '0%';
        this.timeRemaining.textContent = '剩余时间: --:--';
        
        // 显示开始追踪按钮
        this.showStartTrackingButton();
        
        // 返回实时收入页面
        this.backToEarnings();
    }
    
    
    shareResult() {
        // 生成分享文本
        const shareText = `🎉 今日工作完成！\n\n💰 今日收入：￥${this.currentEarnings.toFixed(2)}\n⏰ 实际工作时长：${(this.workDurationSeconds / 3600).toFixed(1)}小时\n📈 工作进度：100%\n📊 本月累计：￥${this.monthlyTotalEarnings.toFixed(2)}\n\n💪 每一秒都在创造价值！\n#智能薪资计算器 #工作成果`;
        
        // 尝试使用Web Share API
        if (navigator.share) {
            navigator.share({
                title: '今日工作结算',
                text: shareText,
                url: window.location.href
            }).catch(err => {
                console.log('分享失败:', err);
                this.copyToClipboard(shareText);
            });
        } else {
            // 如果不支持Web Share API，复制到剪贴板
            this.copyToClipboard(shareText);
        }
    }
    
    copyToClipboard(text) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text).then(() => {
                alert('📋 结算结果已复制到剪贴板！\n\n您可以粘贴到微信、QQ等应用分享给朋友。');
            }).catch(() => {
                this.fallbackCopyToClipboard(text);
            });
        } else {
            this.fallbackCopyToClipboard(text);
        }
    }
    
    fallbackCopyToClipboard(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        try {
            document.execCommand('copy');
            alert('📋 结算结果已复制到剪贴板！\n\n您可以粘贴到微信、QQ等应用分享给朋友。');
        } catch (err) {
            alert('复制失败，请手动复制以下内容：\n\n' + text);
        }
        
        document.body.removeChild(textArea);
    }

    showStartTrackingPrompt() {
        // 检查当前时间是否在工作时间内
        const now = new Date();
        const currentTimeString = now.toTimeString().substr(0, 5);
        
        if (currentTimeString >= this.startTime && currentTimeString <= this.endTime) {
            // 在工作时间内，显示开始追踪的提示
            const startConfirm = confirm('检测到您有保存的工作设置！\n\n当前时间在工作时间内，是否立即开始收入追踪？');
            if (startConfirm) {
                this.startTracking();
            } else {
                this.showStartTrackingButton();
            }
        } else if (currentTimeString < this.startTime) {
            // 还未到上班时间
            const timeToWork = this.getTimeUntilWork();
            alert(`欢迎回来！\n\n距离上班时间还有 ${timeToWork}，您也可以点击"开始追踪"按钮手动开始。`);
            this.showStartTrackingButton();
        } else {
            // 已过下班时间
            alert('欢迎回来！\n\n当前已过下班时间，您也可以点击"开始追踪"按钮手动开始。');
            this.showStartTrackingButton();
        }
    }

    showStartTrackingButton() {
        this.startTrackingBtn.style.display = 'inline-flex';
    }

    hideStartTrackingButton() {
        this.startTrackingBtn.style.display = 'none';
    }

    getTimeUntilWork() {
        const now = new Date();
        const [startHours, startMinutes] = this.startTime.split(':').map(Number);
        const workStart = new Date();
        workStart.setHours(startHours, startMinutes, 0, 0);
        
        const timeDiff = workStart.getTime() - now.getTime();
        const hours = Math.floor(timeDiff / (1000 * 60 * 60));
        const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
        
        if (hours > 0) {
            return `${hours}小时${minutes}分钟`;
        } else {
            return `${minutes}分钟`;
        }
    }

    // 缓存管理方法
    saveToCache() {
        const formData = {
            monthlySalary: this.monthlySalary,
            isProbationPeriod: this.isProbationPeriod,
            workDaysPerWeek: this.workDaysPerWeek,
            startTime: this.startTime,
            endTime: this.endTime,
            lunchBreak: this.lunchBreak,
            monthlyTotalEarnings: this.monthlyTotalEarnings,
            workDaysCompleted: this.workDaysCompleted,
            timestamp: Date.now()
        };
        
        try {
            localStorage.setItem('salaryCalculatorData', JSON.stringify(formData));
            console.log('数据已保存到缓存');
        } catch (error) {
            console.error('保存数据到缓存失败:', error);
        }
    }

    loadFromCache() {
        try {
            const cachedData = localStorage.getItem('salaryCalculatorData');
            if (cachedData) {
                const formData = JSON.parse(cachedData);
                
                // 检查缓存是否过期（24小时）
                const now = Date.now();
                const cacheAge = now - (formData.timestamp || 0);
                const maxAge = 24 * 60 * 60 * 1000; // 24小时
                
                if (cacheAge > maxAge) {
                    console.log('缓存已过期，清除缓存');
                    this.clearCache();
                    return;
                }
                
                // 恢复表单数据
                this.monthlySalary = formData.monthlySalary || 0;
                this.isProbationPeriod = formData.isProbationPeriod || false;
                this.workDaysPerWeek = formData.workDaysPerWeek || 5;
                this.startTime = formData.startTime || '09:00';
                this.endTime = formData.endTime || '18:00';
                this.lunchBreak = formData.lunchBreak || 1;
                this.monthlyTotalEarnings = formData.monthlyTotalEarnings || 0;
                this.workDaysCompleted = formData.workDaysCompleted || 0;
                
                // 填充表单
                this.monthlySalaryInput.value = this.monthlySalary;
                this.isProbationPeriodInput.checked = this.isProbationPeriod;
                this.workDaysPerWeekInput.value = this.workDaysPerWeek;
                this.startTimeInput.value = this.startTime;
                this.endTimeInput.value = this.endTime;
                this.lunchBreakInput.value = this.lunchBreak;
                
                // 自动计算并显示实时收入界面
                if (this.monthlySalary > 0) {
                    console.log('从缓存恢复数据，自动进入实时收入界面');
                    this.calculate();
                    this.showEarningsStep();
                    this.showStartTrackingPrompt();
                }
            }
        } catch (error) {
            console.error('从缓存加载数据失败:', error);
            this.clearCache();
        }
    }

    clearCache() {
        try {
            localStorage.removeItem('salaryCalculatorData');
            console.log('缓存已清除');
        } catch (error) {
            console.error('清除缓存失败:', error);
        }
    }

    // 小窗模式相关方法
    enterMiniMode() {
        if (!this.isTracking && !this.currentEarnings) {
            alert('请先开始收入追踪才能使用小窗模式！');
            return;
        }
        
        this.isMiniMode = true;
        this.miniWindow.style.display = 'block';
        document.body.style.overflow = 'hidden'; // 隐藏主页面滚动条
        
        // 隐藏主界面
        this.setupStep.style.display = 'none';
        this.earningsStep.style.display = 'none';
        
        // 初始化小窗数据
        this.syncMiniDisplay();
        
        // 缩小主窗口到最小尺寸（Electron环境） 
        if (window.electronAPI) {
            window.electronAPI.resizeWindowToMin();
        }
        
        console.log('进入小窗模式');
    }

    exitMiniMode() {
        this.isMiniMode = false;
        this.miniWindow.style.display = 'none';
        document.body.style.overflow = ''; // 恢复滚动条
        
        // 恢复主界面
        this.showEarningsStep();
        
        // 恢复主窗口到正常尺寸（Electron环境）
        if (window.electronAPI) {
            window.electronAPI.resizeWindowToNormal();
        }
        
        console.log('退出小窗模式');
    }

    closeMiniWindow() {
        this.exitMiniMode();
        
        // 确保窗口恢复到正常尺寸
        if (window.electronAPI) {
            window.electronAPI.resizeWindowToNormal();
        }
    }

    updateMiniDisplay(progressPercentage, remainingSeconds) {
        if (!this.isMiniMode) return;
        
        this.miniCurrentEarnings.textContent = this.currentEarnings.toFixed(2);
        this.miniProgressFill.style.width = progressPercentage + '%';
        this.miniProgressPercentage.textContent = progressPercentage.toFixed(1) + '%';
        this.miniTimeRemaining.textContent = this.formatTime(remainingSeconds);
    }

    syncMiniDisplay() {
        // 同步当前状态到小窗
        this.miniCurrentEarnings.textContent = this.currentEarnings.toFixed(2);
        
        // 同步进度条状态
        const currentProgress = this.progressFill.style.width;
        this.miniProgressFill.style.width = currentProgress;
        this.miniProgressPercentage.textContent = this.progressPercentage.textContent;
        this.miniTimeRemaining.textContent = this.timeRemaining.textContent.replace('剩余时间: ', '');
        
        // 同步按钮状态
        if (this.isTracking && !this.isPaused) {
            this.miniPauseBtn.style.display = 'inline-flex';
            this.miniStartBtn.style.display = 'none';
        } else {
            this.miniPauseBtn.style.display = 'none';
            this.miniStartBtn.style.display = 'inline-flex';
        }
    }

    setupMiniWindowDrag() {
        const header = this.miniWindow.querySelector('.mini-header');
        
        header.addEventListener('mousedown', (e) => {
            this.isDragging = true;
            this.miniWindow.classList.add('dragging');
            
            const rect = this.miniWindow.getBoundingClientRect();
            this.dragOffset.x = e.clientX - rect.left;
            this.dragOffset.y = e.clientY - rect.top;
            
            document.addEventListener('mousemove', this.handleMiniDrag.bind(this));
            document.addEventListener('mouseup', this.handleMiniDragEnd.bind(this));
        });
    }

    handleMiniDrag(e) {
        if (!this.isDragging) return;
        
        const x = e.clientX - this.dragOffset.x;
        const y = e.clientY - this.dragOffset.y;
        
        // 限制拖拽范围
        const maxX = window.innerWidth - this.miniWindow.offsetWidth;
        const maxY = window.innerHeight - this.miniWindow.offsetHeight;
        
        const boundedX = Math.max(0, Math.min(x, maxX));
        const boundedY = Math.max(0, Math.min(y, maxY));
        
        this.miniWindow.style.left = boundedX + 'px';
        this.miniWindow.style.top = boundedY + 'px';
        this.miniWindow.style.right = 'auto'; // 取消默认的right定位
    }

    handleMiniDragEnd() {
        this.isDragging = false;
        this.miniWindow.classList.remove('dragging');
        
        document.removeEventListener('mousemove', this.handleMiniDrag.bind(this));
        document.removeEventListener('mouseup', this.handleMiniDragEnd.bind(this));
    }

    // 重写一些方法以支持小窗模式
    togglePause() {
        if (!this.isTracking) return;

        if (this.isPaused) {
            // 继续
            this.isPaused = false;
            this.pauseBtn.innerHTML = '⏸ 暂停';
            this.pauseBtn.style.background = 'rgba(255, 255, 255, 0.8)';
            
            // 小窗模式按钮同步
            if (this.isMiniMode) {
                this.miniPauseBtn.style.display = 'inline-flex';
                this.miniStartBtn.style.display = 'none';
            }
            
            this.intervalId = setInterval(() => {
                this.updateDisplay();
            }, 1000);
        } else {
            // 暂停
            this.isPaused = true;
            this.pauseBtn.innerHTML = '▶ 继续';
            this.pauseBtn.style.background = '#28a745';
            this.pauseBtn.style.color = 'white';
            
            // 小窗模式按钮同步
            if (this.isMiniMode) {
                this.miniPauseBtn.style.display = 'none';
                this.miniStartBtn.style.display = 'inline-flex';
            }
            
            if (this.intervalId) {
                clearInterval(this.intervalId);
                this.intervalId = null;
            }
        }
    }

    // 重写reset方法以支持小窗模式
    reset() {
        this.stopTracking();
        this.clearCache();
        
        // 如果在小窗模式，先退出
        if (this.isMiniMode) {
            this.exitMiniWindow();
        }
        
        // 隐藏所有页面
        this.setupStep.style.display = 'none';
        this.earningsStep.style.display = 'none';
        this.settlementStep.style.display = 'none';
        
        this.showSetupStep();
        this.form.reset();
        this.startTimeInput.value = '09:00';
        this.endTimeInput.value = '18:00';
        this.workDaysPerWeekInput.value = '5';
        this.lunchBreakInput.value = '1';
        this.isProbationPeriodInput.checked = false;
        
        // 重置所有变量
        this.monthlySalary = 0;
        this.workDaysPerWeek = 5;
        this.lunchBreak = 1;
        this.isProbationPeriod = false;
        this.currentEarnings = 0;
        this.monthlyTotalEarnings = 0;
        this.workDaysCompleted = 0;
        this.isTracking = false;
        this.isPaused = false;
        this.pausedTime = 0;
        
        // 隐藏开始追踪按钮
        this.hideStartTrackingButton();
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new SalaryCalculator();
});

// 添加一些实用工具函数
const Utils = {
    // 格式化货币
    formatCurrency(amount) {
        return new Intl.NumberFormat('zh-CN', {
            style: 'currency',
            currency: 'CNY'
        }).format(amount);
    },
    
    // 获取当前时间字符串
    getCurrentTimeString() {
        return new Date().toTimeString().substr(0, 8);
    },
    
    // 检查是否为工作日
    isWorkDay(date = new Date()) {
        const day = date.getDay();
        return day >= 1 && day <= 5; // 周一到周五
    }
};

// 添加页面可见性检测，当标签页不可见时暂停计算，可见时恢复
document.addEventListener('visibilitychange', () => {
    // 这里可以添加页面可见性变化的处理逻辑
    if (document.hidden) {
        console.log('页面隐藏，可考虑暂停计算以节省资源');
    } else {
        console.log('页面显示，恢复计算');
    }
});
